package com.ezlcp.user.utils;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author Elwin ZHANG
 * @description: Nacos工具类<br />
 * @date 2022/12/22 10:08
 */
@Component
@Slf4j
public class NacosUtils {

    @Value("${spring.cloud.nacos.config.server-addr:localhost}")
    private String serverAddr;

    @Value("${spring.cloud.nacos.config.namespace:default}")
    private String nameSpace;

    @Value("${spring.cloud.nacos.config.prefix:}")
    private String prefix;

    /***
    * @description 关闭Nacos的配置服务
    * @param service 服务对象
    * @author Elwin ZHANG
    * @date 2022/12/22 10:57
    */
    public void closeService(ConfigService service) {
        try {
            service.shutDown();
        } catch (Exception e) {
            log.info("========关闭Nacos的配置服务时出错：");
            log.error(e.getMessage(), e);
        }
    }

    /***
     * @description 获取Nacos的配置服务
     * @return com.alibaba.nacos.api.config.ConfigService
     * @author Elwin ZHANG
     * @date 2022/12/22 10:27
     */
    public ConfigService getConfigService() {
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        properties.put("namespace", nameSpace);
        properties.put("prefix",prefix);
        try {
            return NacosFactory.createConfigService(properties);
        } catch (Exception e) {
            log.info("========获取Nacos的配置服务时出错：");
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
